package com.bj58.analysis.tools.source;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


import net.sf.json.JSONObject;

import com.bj58.analysis.tools.etl.bean.ETLTrackBean;

public class PCMSourceFormat {
	private static Map<String,String> pc_marktSpmMap = new HashMap<String,String>();
	private static Map<String,String> m_marktSpmMap = new HashMap<String,String>();
	private static Map<String,String> pc_qd_map = new HashMap<String,String>();
	private static Map<String,String> m_lm_map = new HashMap<String,String>();
	private static Map<String,String> m_qd_map = new HashMap<String,String>();
	private static String platform = "";
	private static String url = "";
	private static String domain = "";
	private static String utmSource = "";
	private static String marketspm = "";
	private static String userAgent="";
	private static String initRef = "";
	private static String trackURL="";
	private static String pagetype="";
	private static String[] seoDomain = {".baidu.", ".so.",".haosou.", ".google.",
			".sogou.", ".soso.", ".bing.", ".yahoo.", ".youdao.",".ask.",".easou.",".sm.",".shenma.",".ucweb."};


	/**
	 *
	* getSourceName(取出来源字符串,用\t分割)
	* @auther caods
	* @param SourceNameEntity实体类
	* @return String DOM对象
	* @Exception 异常对象
	* @since  CodingExample　Ver(编码范例查看) 1.1
	 */
	public static String getSourceName(SourceNameEntity sourceBean)
	{
		String sourceName = "";
		try{
			if(sourceBean!=null){
				platform = sourceBean.getPlatform()!=null?sourceBean.getPlatform():"";
				if(sourceBean.getTrackInfo()!=null){
					ETLTrackBean trackInfo = sourceBean.getTrackInfo();
					url = trackInfo.getUrl()==null?"":trackInfo.getUrl();
					userAgent = trackInfo.getUserAgent()==null?"":trackInfo.getUserAgent();//UA头
					pagetype = trackInfo.getPageType()==null?"":trackInfo.getPageType();
					trackURL = trackInfo.getTrackUrl()==null?"":trackInfo.getTrackUrl();
					JSONObject trackUrlJson = JSONObject.fromObject(trackURL);
					if(trackUrlJson!=null){
						utmSource = trackUrlJson.get("utm_source")!=null?trackUrlJson.get("utm_source").toString():"";
						marketspm = trackUrlJson.get("spm")!=null?trackUrlJson.get("spm").toString():"";
						initRef   = trackUrlJson.get("init_refer")!=null?trackUrlJson.get("init_refer").toString():"";
						domain 	  = initRef.indexOf("?")>0?initRef.substring(0, initRef.indexOf("?")):initRef;
					}
				}else{
					url 		= sourceBean.getUrl()!=null?sourceBean.getUrl():"";
					userAgent	= sourceBean.getUserAgent()!=null?sourceBean.getUserAgent():"";
					pagetype 	= sourceBean.getPageType()!=null?sourceBean.getPageType():"";
					utmSource 	= sourceBean.getUtmSource()!=null?sourceBean.getUtmSource():"";
					marketspm 	= sourceBean.getMarketSpm()!=null?sourceBean.getMarketSpm():"";
					initRef 	= sourceBean.getInitRef()!=null?sourceBean.getInitRef():"";
					domain 	  = initRef.indexOf("?")>0?initRef.substring(0, initRef.indexOf("?")):initRef;
				}
				url       = url.toLowerCase().equals("null")?"":url;
				userAgent = userAgent.toLowerCase().equals("null")?"":userAgent;
				pagetype  = pagetype.toLowerCase().equals("null")?"":pagetype;
				utmSource = utmSource.toLowerCase().equals("null")?"":utmSource;
				marketspm = marketspm.toLowerCase().equals("null")?"":marketspm;
				initRef   = initRef.toLowerCase().equals("null")?"":initRef;
				domain    = domain.toLowerCase().equals("null")?"":domain;

//				//解析字典表
//				analysisDict(sourceBean.getMarkt_spm_list(), sourceBean.getPc_qd_list(), sourceBean.getM_lm_list(), sourceBean.getM_qd_list());
				//解决跨域名访问导致的问题
				if(isKuayu(url)&&!sourceBean.getPreviousSource().equals("")){
					sourceName = sourceBean.getPreviousSource();
					sourceName ="跨域";
					return sourceName;
				}
				//根据平台调取对应的方法
				if(platform.toLowerCase().equals("pc"))
				{
					sourceName = getPCSourceName();
				}else if(platform.toLowerCase().equals("m"))
				{
					sourceName = getMSourceName();
				}else{
					sourceName ="其他";
				}
			}else{
				sourceName="其他";
			}
		}catch(Exception e){
			sourceName = platform.toLowerCase().equals("pc")?"其他":"other\tother";
		}
		return sourceName;

	}

	//判断跨域名
	public static Boolean isKuayu(String url){
		boolean flag = false;
		String[] arrys = "58cdn,5858,58che,jxedt,58kuaipai,58supin".split(",");
		for (String str : arrys) {
			if(url.indexOf(str)!=-1){
				return true;
			}
		}
		return flag;
	}
	public static void initDict(List<String> marktSpmList,List<String> pc_qd_list,List<String> m_lm_list,List<String> m_qd_list){
		//---------------------------begin 组装字典表Map-------------------------------------------------------
		if(m_lm_list!=null){
			//m端联盟字典表
			for (String name : m_lm_list) {
				String[] strArr = name.split("\t", -1);
				m_lm_map.put(strArr[0], strArr[1]);
			}
		}
		if(m_qd_list!=null){
			//m端渠道字典表
			for (String name : m_qd_list) {
				String [] array=name.split("\t",-1);
				m_qd_map.put(array[0],array[1]+"\t"+array[2]+"\t"+array[3]);
			}
		}
		if(pc_qd_list!=null){
			//pc端渠道字典表
			for (String name : pc_qd_list) {
			    String[] strArr = name.split("\t", -1);
			    if(!strArr[0].toLowerCase().equals("seo")){
			    	 pc_qd_map.put(strArr[3], strArr[0]+"\t"+strArr[1]+"\t"+strArr[2]);
			    }
			}
		}

		if(marktSpmList!=null){
			//新的spm字典表
			for (String marktspm : marktSpmList) {
				String[] strArr = marktspm.split("\t", -1);
				String spmKey = strArr[0]+"."+strArr[1];
				if(strArr[2].equals("PC端") && strArr[0].indexOf("b-32948702282246-")==-1 && strArr[0].indexOf("b-12345678901234-")==-1){
					String source1 = strArr[3];
					if(strArr[3].equals("58系PC")){
						source1 = "58系PC站点";
					}
					String spmVal = source1 + "\t" + strArr[4] + "\t" + strArr[5];
					pc_marktSpmMap.put(spmKey, spmVal);
				}
				if (strArr[2].equals("移动端") && strArr[0].indexOf("b-32948702282246-")==-1 && strArr[0].indexOf("b-12345678901234-")==-1) {
			        String source1 = "";
			        if (strArr[3].equals("付费其他") || strArr[3].equals("付费其它"))
			        	source1 = "fufeiqita";
			        else if (strArr[3].equals("付费浏览器"))
			        	source1 = "fufeiliulanqi";
			        else if (strArr[3].equals("58系APP"))
			        	source1 = "58系APP站点";
			        else if (strArr[3].equals("58系M"))
			        	source1 = "58系M站点";
			        else {
			        	source1 = strArr[3];
			        }
			        String spmVal = source1 + "\t" + strArr[4] + "\t" + strArr[5];
			        m_marktSpmMap.put(spmKey, spmVal);
			     }
			}
		}

		//------------------------------end 组装字典表结束--------------------------------------------
	}

	private static String getPCSourceName(){
		String sourceName = "其他";
		if(!marketspm.equals("") || !utmSource.equals("")){
			if (!marketspm.equals("") && pc_marktSpmMap.get(marketspm) != null){
				sourceName = pc_marktSpmMap.get(marketspm);
				return sourceName;
		    }
			else if(!marketspm.equals("") && m_lm_map.get(marketspm.split("\\.")[0]) != null){
				sourceName = "联盟\t" +m_lm_map.get(marketspm.split("\\.")[0]);
				return sourceName;
			}
			else if(!utmSource.equals("") && pc_qd_map.get(utmSource)!=null ){
				sourceName = pc_qd_map.get(utmSource);
				return sourceName;
			}
			else if (!utmSource.equals("") && (utmSource.contains("email") || utmSource.toLowerCase().contains("edm") )){
				sourceName = "EDM";
				return sourceName;
			}
			else{
				sourceName = "付费未知其他";
				return sourceName;
			}
		}else{
			if(domain.equals("")){
				sourceName = "直接访问";
				return sourceName;
			}
			else{
				if(domain.contains(".58.com")){
					sourceName = "站内引荐";
					return sourceName;
				}
				else{
					if(domain.contains("www.hao123.com")){
						sourceName = "付费导航" + "\t" + "hao123导航";
						return sourceName;
					}
					else if(!isSearch().equals("") ){
						sourceName = "SEO"+"\t"+isSearch();
						return sourceName;
					}
					else{
						sourceName = "站外引荐";
						return sourceName;
					}
				}
			}
		}
	}
	private static String getMSourceName(){
		String sourceName = "其他";
		if(!marketspm.equals("") || !utmSource.equals("")){
			if (!marketspm.equals("") && m_marktSpmMap.get(marketspm) != null){
				sourceName = m_marktSpmMap.get(marketspm);
				return sourceName;
		    }
			else if(!marketspm.equals("") && m_lm_map.get(marketspm.split("\\.")[0]) != null){
				//这么取spm，是因为老的联盟字典表里面只有code1，所以要截取日志中spm的code1
				String lm_spm = marketspm.split("\\.")[0];
				if(m_lm_map.get(lm_spm).equals("手机QQ")){
					sourceName = "手机QQ";
				}else if(m_lm_map.get(lm_spm).equals("momo")){
					sourceName = "陌陌";
				}else{
					sourceName = "联盟" +"\t"+ m_lm_map.get(lm_spm);
				}
				return sourceName;
			}
		    else if(!utmSource.equals("") && m_qd_map.get(utmSource)!=null ){
				sourceName = m_qd_map.get(utmSource);
				if (utmSource.equals("mzt_shouq_googzh")) {
					sourceName = "other" +"\t"+ "wei-手Q服务号";
			    }else {
			    	sourceName = m_qd_map.get(utmSource);
			    }
				return sourceName;
			}
			else{
				sourceName = "付费未知其他";
				return sourceName;
			}
		}else{
			if(userAgent.indexOf("baiduboxapp")!=-1){
				sourceName = "SEO" +"\t"+ "baiduboxapp";
				return sourceName;
			}
			else if(url.indexOf("http://w.58.com/poster/zp/") != -1){
				sourceName = "other" +"\t"+ "weizhaopin";
				return sourceName;
			}
			else if(url.indexOf("http://w.58.com/wfc/detail/") != -1){
				sourceName = "other" +"\t"+ "weifangchan";
				return sourceName;
			}
			else if(url.indexOf("http://w.58.com/wzp/detailH5") != -1){
				sourceName = "other" +"\t"+ "weizhaopin";
				return sourceName;
			}
			else if(pagetype.equals("weidian")){
				sourceName = "other" +"\t"+ "weidian";
				return sourceName;
			}
			else if(userAgent.toLowerCase().indexOf("__weibo__") != -1)//__weibo__
			{
				sourceName = "other" +"\t"+ "weibo";
				return sourceName;
			}
			else if(userAgent.toLowerCase().indexOf("micromessenger") != -1)//MicroMessenger
			{
				sourceName = "other" +"\t"+ "weixin";
				return sourceName;
			}
			else if(url.indexOf("qq-pf-to") != -1)
			{
				sourceName = "other" +"\t"+ "qqclient";//qq
				return sourceName;
			}
			else{
				if(domain.equals("")){
					sourceName = "直接访问";
					return sourceName;
				}else{
					if(domain.contains(".58.com")){
						sourceName = "站内引荐";
						return sourceName;
					}else{
						if(!isSearch().equals("")){
							sourceName = "SEO"+"\t"+isSearch();
							return sourceName;
						}else{
							sourceName = "站外引荐";
							return sourceName;
						}
					}
				}
			}
		}
	}

	//判断是否包含seo域名
	private static String isSearch(){
		for (String seoStr : seoDomain){
			if (domain.contains(seoStr))
				return seoStr.replace(".", "");
		}
		return "";
	}

}
